package edu.ccut.saturn.component.impl.node;

import edu.ccut.saturn.component.ComponentManager;
import edu.ccut.saturn.component.DatabaseBroker;
import edu.ccut.saturn.component.ILogicContext;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.loader.node.NodeInfoLoader;
import edu.ccut.saturn.component.loader.node.TransactionRollBackNodeInfoLoader;
import edu.ccut.saturn.component.utils.ExceptionUtils;
import edu.ccut.saturn.component.xml.ISaturnElement;
import edu.ccut.saturn.component.xml.SaturnElement;

/**
 * 事务回滚结点的实现类。在logic组件中调用事务回滚结点，表示在JDBC事务范围内回滚所有的数据库操作。
 * 
 * @author 温建
 * 
 * @version 1.0 2008.8.21
 * 
 * @see AbstractNodeInfo
 * @see ILogicContext
 * @see DatabaseBroker
 * 
 */
public class TransactionRollBackNodeInfo extends AbstractNodeInfo {

	public TransactionRollBackNodeInfo(String id, String name,
			String description, String nextId, String x, String y) {

		super(id, name, description, nextId, null, x, y, "transactionRollBack");
	}

	/**
	 * 事务回滚结点的执行逻辑。 需要调用上下文中的数据库代理对象的方法来在JDBC事务范围内，回滚所有的数据库操作。
	 * 
	 * @param logicContext
	 *            逻辑上下文对象，记录结点运行时的上下文信息
	 */
	@Override
	public void doExecute(ILogicContext logicContext) throws Exception {
		ComponentManager.beforeExecuteComponent(this, null);

		try {
			logicContext.getDatabaseBroker().rollbackTracsaction();
		} catch (Exception e) {
			logger.error("ERROR : {message :'" + ExceptionUtils.getExMessage(e) + "', process : '" + logicContext.getId() + "', node : '" +
					 super.getNodeType() + " " + super.getId() + " " + super.getName() + "'}");

			throw e;

		} finally {
			ComponentManager.afterExecuteComponent(this, null);
		}
	}

	@Override
	protected IParameterContext createParameterContext(
			ILogicContext logicContext) throws Exception {

		return null;
	}

	public ISaturnElement toSaturnElement() {
		ISaturnElement transactionRollBackElement = new SaturnElement(
				TransactionRollBackNodeInfoLoader.KEY_NODETYPE_TRANSACTION_ROLLBACK);

		transactionRollBackElement.addAttribute(NodeInfoLoader.KEY_NODE_ID,
				this.getId());

		transactionRollBackElement.addAttribute(NodeInfoLoader.KEY_NODE_NEXT,
				this.getNextId());

		transactionRollBackElement.addAttribute(NodeInfoLoader.KEY_NODE_X, this
				.getX());

		transactionRollBackElement.addAttribute(NodeInfoLoader.KEY_NODE_Y, this
				.getY());

		ISaturnElement nameElement = new SaturnElement(
				NodeInfoLoader.KEY_NODE_NAME, this.getName());

		ISaturnElement descriptionElement = new SaturnElement(
				NodeInfoLoader.KEY_NODE_DESCRIPTION, this.getDescription());

		transactionRollBackElement.addSubElement(nameElement);
		transactionRollBackElement.addSubElement(descriptionElement);
		return transactionRollBackElement;
	}
}
